<template>
    <div ref="dragListRef" class="drag">
        <div class="item-box" v-for="item in list" :key="item.id">
            <span :style="`background-color: ${item.color}`">{{ item.name }}</span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useSortable, moveArrayElement } from '@vueuse/integrations/useSortable'
// Parent
const dragListRef = ref<HTMLDivElement>()
interface DragSortListType {
    id: number
    index: number
    name: string
    color: string
}
// 要排序的数组
const list = computed((): DragSortListType[] => {
    const l: DragSortListType[] = []
    for (let i = 0; i < 16; i++) {
        l.push({
            id: i,
            index: i,
            name: `${i}`,
            color: getRandomColor(),
        })
    }
    return l
})
useSortable(dragListRef, list, {
    animation: 300,
    onUpdate: (e: any) => {
        // 移动元素在数组中的位置
        moveArrayElement(list.value, e.oldIndex, e.newIndex)
        nextTick(() => {
            // 修改自定义的index属性
            list.value.forEach((item, index) => (item.index = index))
        })
    },
})
</script>

<style lang="scss" scoped>
.drag {
    display: grid;
    grid-template-rows: repeat(4, 1fr);
    grid-template-columns: repeat(4, 1fr);
    height: calc(100vh - 50px - 40px - 10px * 2 - 20px * 2 - 2px);

    .item-box {
        display: flex;
        justify-content: center;
        align-items: center;
        user-select: none;
        cursor: move;

        span {
            display: flex;
            justify-content: center;
            align-items: center;

            width: calc(100% - 5px * 8);
            height: calc(100% - 5px * 8);

            border-radius: 10px;
            box-shadow: 0 0 10px rgba($color: #3d3a3a, $alpha: 0.8);
            font-size: 50px;
        }
    }
}
</style>
